//
//  WHWriteLogTool.m
//  WHPersonalData
//
//  Created by shengmeng chen on 2020/12/5.
//  Copyright © 2020 mac. All rights reserved.
//

#import "WHWriteLogTool.h"

@implementation WHWriteLogTool

#pragma mark 使用NSSearchPathForDirectoriesInDomains创建文件目录
+(void)writeLogInfomation:(NSString*)information {
    
    NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *dataFilePath = [docsdir stringByAppendingPathComponent:@"LOG"];
    // 在Document目录下创建 "archiver" 文件夹
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *str = [formatter stringFromDate:[NSDate date]];
    dataFilePath =[NSString stringWithFormat:@"%@/AppExchlog_%@",dataFilePath,str];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    // fileExistsAtPath 判断一个文件或目录是否有效，isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:dataFilePath isDirectory:&isDir];
    if (!(isDir && existed)) {
        // 在Document目录下创建一个archiver目录
        [fileManager createDirectoryAtPath:dataFilePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    // 在archiver下写入文件
    NSString *path = [dataFilePath stringByAppendingPathComponent:@"log.txt"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *datestr = [dateFormatter stringFromDate:[NSDate date]];
    NSString *crashString = [NSString stringWithFormat:@"\n%@\n%@",datestr,information];
    
    //BGK编码
    NSStringEncoding gbkEncoding =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    //把错误日志写到文件中
    if (![fileManager fileExistsAtPath:path]) {
        
           [crashString writeToFile:path atomically:YES encoding:gbkEncoding error:nil];
    }else{
            NSFileHandle *outFile = [NSFileHandle fileHandleForWritingAtPath:path];
            [outFile seekToEndOfFile];
            [outFile writeData:[crashString dataUsingEncoding:gbkEncoding]];
            [outFile closeFile];
    }
}

@end
